import { Card, Row, Col, DatePicker, Table, Form, Button, Modal, Upload, Icon, Checkbox, message } from 'antd';
import React, { Component }from 'react';

import *as XLSX from 'xlsx';
import styles from '../style.less';


const options = [
    { label: '全部', value: 'all' },
    { label: '企业概况', value: 'qiyegaikuang' },
    { label: '企业经营数据', value: 'jingyingshuju' },
    { label: '主营产品', value: 'zhuyingchanpin' },
    { label: '科技创新（核心技术及研发）', value: 'kejichuangxin' },
    { label: '产业资金奖励情况', value: 'zijinjiangli' },
    { label: '主要荣誉', value: 'zhuyaorongyu' },
    { label: '企业诉求', value: 'qiyesuqiu' },
    { label: '产品自荐入库理由', value: 'rukuliyou' }
]



class ExportButton extends Component {
    state = {
        showModal: false,
        checked: [],
    }


    componentDidMount = () => {

    }

    saveFormRef = formRef => {
        this.formRef = formRef
    }

    btnHandleClick = () => {
        // 清空选项
        this.setState({
            showModal: true,
        })
    }

    onCancel = () => {
        this.setState({ showModal: false })
    }

    onOk = () => {
        // console.log(this.state.checked)
        const { selectedRowKeys, data } = this.props
        // console.log(selectedRowKeys)
        // console.log(data)

        if (selectedRowKeys.length === 0 || this.state.checked.length === 0) {
            message.info('请选择要导出的企业和要导出的内容！')
            return;
        }
        const nowdata = []

        

        // eslint-disable-next-line array-callback-return
        selectedRowKeys.map(item => {
            data.forEach((val, index) => {
                if (val.key === item) {
                    nowdata.push({
                        name: data[index].name,
                        // 所在街道
                        street: data[index].street,
                        // 行业类型
                        industry: data[index].industry,
                        // 产品数量
                        numble: data[index].numble,
                        // 法人代表
                        owner: data[index].owner,
                        // 联系电话
                        phone: data[index].phone,
                    })
                }
            })
        })
        
        // eslint-disable-next-line no-console
        console.log('导出爆表')
        const entozh = {
            "name":"企业名称",
            "street":"所在街道",
            "industry":"行业类型",
            "numble":"产品数量",
            "owner":"法人代表",
            "phone":"联系电话",
          }

        const json = nowdata.map(item => {

            return Object.keys(item).reduce((newData, key) => {
                const newKey = entozh[key] || key
                newData[newKey] = item[key]
                return newData
            }, {})
        });


        const sheet = XLSX.utils.json_to_sheet(json);

        this.openDownloadDialog(this.sheet2blob(sheet,undefined), `企业信息.xlsx`);
        
        this.setState({
            showModal: false,
        })
        
    }

    sheet2blob = (sheet, sheetName) => {
        // eslint-disable-next-line no-param-reassign
        sheetName = sheetName || 'sheet1';
        const workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet; // 生成excel的配置项
  
        const wopts = {
          bookType: 'xlsx', // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          type: 'binary'
        };
        const wbout = XLSX.write(workbook, wopts);
        const blob = new Blob([s2ab(wbout)], {
          type: "application/octet-stream"
        }); // 字符串转ArrayBuffer
        function s2ab(s) {
          const buf = new ArrayBuffer(s.length);
          const view = new Uint8Array(buf);
          // eslint-disable-next-line no-bitwise
          for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }
        return blob;
    }

    openDownloadDialog = (url, saveName) => {
        if (typeof url == 'object' && url instanceof Blob) {
          url = URL.createObjectURL(url); // 创建blob地址
        }
        const aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        let event;
        if (window.MouseEvent) event = new MouseEvent('click');
        else {
          event = document.createEvent('MouseEvents');
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
    }

    onChange = checkedList => {
        const { checked } = this.state
        if (!checkedList.includes('all') && checked.includes('all')) {
            this.setState({
                checked: []
            })
            return
        }
        if (checkedList.includes('all') && !checked.includes('all')) {
            const checkedAll = []
            options.forEach(val => {
                checkedAll.push(val.value)
            })
            this.setState({
                checked: checkedAll
            })
            return
        }

        this.setState({
            checked: checkedList
        })

    }
    
    render () {

        return (
            <>
                <Button 
                    icon="arrow-up" 
                    type="primary" 
                    className={styles.upCompany} 
                    onClick={this.btnHandleClick}
                >
                    导出报表
                </Button>
                <Modal
                    visible={this.state.showModal}
                    title="导出内容（多选）"
                    onCancel={this.onCancel}
                    onOk={this.onOk}
                >
                    <Form className={styles.exportCompanyForm}>
                        <Checkbox.Group 
                            options={options}
                            onChange={this.onChange}
                            value={this.state.checked}
                        />
                    </Form>
                </Modal>
            </>
        )
    }
}


export default ExportButton
